package org.example.judge_admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.example.judge_admin.mapper.UserMapper;
import org.example.judge_admin.service.AuthService;
import org.example.judge_admin.service.UserAuthService;
import org.example.judge_admin.service.UserService;
import org.example.judge_common.entity.PageResult;
import org.example.judge_common.entity.RequestParams;
import org.example.judge_common.entity.RequestUserParams;
import org.example.judge_common.util.IdWorker;
import org.example.judge_common.util.MyUtils;
import org.example.judge_feign_api.CommentClient;
import org.example.judge_pojo.Auth;
import org.example.judge_pojo.Mail;
import org.example.judge_pojo.User;
import org.example.judge_pojo.UserAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;

@Service("UserServiceImpl")
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private IdWorker idWorker;

    @Qualifier("AuthServiceImpl")
    @Autowired
    private AuthService authService;
    @Qualifier("UserAuthServiceImpl")
    @Autowired
    private UserAuthService userAuthService;

    @Autowired
    private CommentClient commentClient;
    @Override
    public boolean save(User entity) {
        if(MyUtils.isEmpty(entity.getId()))entity.setId(idWorker.nextId().toString());
        entity.setUpdateTime(new Date());
        entity.setCreateTime(new Date());
        if(MyUtils.isEmpty(entity.getPassword()))entity.setPassword("123456");  //默认密码
        String newPassword = new BCryptPasswordEncoder().encode(entity.getPassword());
        entity.setPassword(newPassword);
        entity.setStatus(0);  //默认可用
        //获取默认权限id
        Auth auth = authService.getAuthByCode(Auth.CLIENT);
        if(auth!=null){//添加默认权限
            UserAuth userAuth = new UserAuth();
            userAuth.setUserId(entity.getId());
            userAuth.setAuthId(auth.getId());
            userAuthService.save(userAuth);
        }
        //发送系统消息
        Mail mail = new Mail();
        mail.setTitle("系统通知");
        mail.setTo(entity.getId());
        mail.setText(Mail.HELLO);
        mail.setUserId("1");
        commentClient.sendMail(mail);
        return super.save(entity);
    }

    @Override
    public boolean updateById(User entity) {
        entity.setUpdateTime(new Date());
        if(MyUtils.isNotEmpty(entity.getPassword())){  //修改密码
            String newPassword = new BCryptPasswordEncoder().encode(entity.getPassword());
            entity.setPassword(newPassword);
        }


        return super.updateById(entity);
    }

    @Override
    public User getById(Serializable id) {

        User byId = super.getById(id);
        if (byId==null) {
            return null;
        }
        byId.setPassword(null);
        List<Auth> list = authService.listByUserId(id.toString(),null,false);
        byId.setAuths(list);
        return byId;
    }

    @Override
    public PageResult<User> search(RequestUserParams params) {
        if(MyUtils.isEmpty(params.getField())){ //默认排序字段
            params.setField(RequestParams.DefaultField);
        }
        if(MyUtils.isEmpty(params.getOrder())){   //默认排序方式
            params.setOrder(RequestParams.DefaultOrder);
        }

        QueryWrapper<User> queryWap = new QueryWrapper<>();

        //字段模糊匹配
        if(MyUtils.isNotEmpty(params.getKey())){
            queryWap.and(new Consumer<QueryWrapper<User>>() { //隔离or条件
                @Override
                public void accept(QueryWrapper<User> problemQueryWrapper) {
                    problemQueryWrapper.like("phone",params.getKey()).or().
                            like("username",params.getKey()).or().
                            like("email",params.getKey()).or().
                            like("school",params.getKey());
                }
            });

        }
        //学校模糊匹配
        if(MyUtils.isNotEmpty(params.getSchool())){
            queryWap.and(new Consumer<QueryWrapper<User>>() { //隔离or条件
                @Override
                public void accept(QueryWrapper<User> problemQueryWrapper) {
                    problemQueryWrapper.likeLeft("school",params.getSchool());
                }
            });

        }

        //性别
        if(params.getSex()!=null&&params.getSex()>=0&&params.getSex()<=1){
            queryWap.eq("sex",params.getSex());
        }
        //状态
        if(params.getStatus()!=null&&params.getStatus()>=0&&params.getStatus()<=1){
            queryWap.eq("status",params.getStatus());
        }

        //排序
        queryWap.orderBy(true,"asc".equalsIgnoreCase(params.getOrder()),params.getField());


        //设置分页
        PageHelper.startPage(params.getPage(), params.getSize(),false);
        List<User> users = this.baseMapper.selectList(queryWap);
        for (User u : users) {
            u.setPassword(null);
            //权限
            List<Auth> auths = authService.listByUserId(u.getId(), 2, false);
            //List<Auth> list = authService.listByUserId(u.getId(),null);
            u.setAuths(auths);
        }
        //求数据条数
        Integer count = this.baseMapper.selectCount(queryWap);
        return new PageResult<User>(count.longValue(),users);
    }

    @Override
    public boolean removeById(Serializable id) {
        userAuthService.removeByUserId(id);
        return super.removeById(id);
    }

    @Override
    public boolean addRating(String userId, Integer rating) {
        return super.baseMapper.addRatingById(userId,rating);
    }

    @Override
    public User selectByEmail(String email) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email",email);
        User one = super.getOne(userQueryWrapper);
        return one;
    }

    @Override
    public User getUsernameOne(String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        PageHelper.startPage(1, 1,false);
        List<User> users = this.baseMapper.selectList(userQueryWrapper);
        if(users==null||users.size()==0)return null;
        return users.get(0);
    }

    @Override
    public Integer getUserRatingRank(String id) {
        this.baseMapper.setRank(0);
        return this.baseMapper.getUserRatingRank(id);
    }
}
